import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';
import { useChatStore } from '../stores/chat';
import { useSystemStore } from '../stores/system';
import userHandler from '@/webSocket/handler/index.js';
import messageEntityBuilder from './type';

class WsUtil {
  constructor() {
    this.wsClient = null; // WebSocket 客户端
    this.heartbeatId = null; // 心跳定时器 ID
    this.retryIntervalId = null; // 重试定时器 ID
    this.maxRetries = 5; // 最大重试次数
  }

  /**
   * 初始化会话、消息、联系人申请
   */
  initSession() {
    if (this.wsClient && this.wsClient.readyState === WebSocket.OPEN) {
      this.sendNotice(messageEntityBuilder.initSession());
    } else {
      console.warn('无法初始化会话，WebSocket 未连接');
    }
  }

  /**
   * 初始化 WebSocket 连接
   */
  initWebSocket() {
    const userStore = useUserStore();
    if (!userStore.token) {
      console.error('Token 为空，无法建立 WebSocket 连接');
      ElMessage({ type: 'error', message: '未登录，请先登录！', plain: true });
      return;
    }

    console.log('当前链接：' , this.wsClient)
    // 防止重复连接
    if (this.wsClient && this.wsClient.readyState !== WebSocket.CLOSED && this.wsClient.readyState !== WebSocket.CLOSING) {
      console.log('WebSocket 已存在或正在连接，跳过初始化');
      return;
    }

    this.wsClient = new WebSocket(`ws://localhost:8889/ws?token=${userStore.token}`);

    this.wsClient.onopen = () => {
      console.log('WebSocket 连接已建立');
      // 清理重试定时器
      if (this.retryIntervalId) {
        clearInterval(this.retryIntervalId);
        this.retryIntervalId = null;
      }
      // 初始化会话并启动心跳
      this.initSession();
      this.heartbeat();
    };

    this.wsClient.onmessage = (result) => {
      console.log('收到消息：', result.data)
      try {
        const data = JSON.parse(result.data);
        if (userHandler[data.type]) {
          if (!data.type.includes('init')) {
            useSystemStore().playNoticeSound();
          }
          userHandler[data.type](data);
        }
      } catch (error) {
        console.error('解析 WebSocket 消息失败:', error);
      }
    };

    this.wsClient.onerror = (err) => {
      console.error('WebSocket 连接错误:', err);
      this.cleanup(); // 清理资源
      if (!this.retryIntervalId) {
        this.retry();
      }
    };

    this.wsClient.onclose = (event) => {
      console.log('WebSocket 连接关闭:', { code: event.code, reason: event.reason, wasClean: event.wasClean });
      this.cleanup(); // 清理资源
      // if (!this.retryIntervalId) {
      //   this.retry();
      // }
    };
  }

  /**
   * 清理 WebSocket 和定时器
   */
  cleanup() {
    if (this.wsClient && this.wsClient.readyState !== WebSocket.CLOSED && this.wsClient.readyState !== WebSocket.CLOSING) {
      this.wsClient.close(1000, 'Normal closure');
    }
    this.wsClient = null;
    if (this.heartbeatId) {
      clearInterval(this.heartbeatId);
      this.heartbeatId = null;
    }
    if (this.retryIntervalId) {
      clearInterval(this.retryIntervalId);
      this.retryIntervalId = null;
    }
  }

  /**
   * 关闭 WebSocket 连接
   */
  close() {
    console.log('尝试关闭 WebSocket，当前 wsClient:', this.wsClient);
    if (this.wsClient && this.wsClient.readyState !== WebSocket.CLOSED && this.wsClient.readyState !== WebSocket.CLOSING) {
      console.log('执行 WebSocket 关闭');
      this.wsClient.close(1000, 'Normal closure');
    } else {
      console.log('WebSocket 已关闭或未初始化，无需关闭');
    }
    this.cleanup(); // 清理资源
  }

  /**
   * 连接重试
   */
  retry() {
    if (this.retryIntervalId) {
      console.log('已有重试定时器，跳过重试');
      return;
    }

    let count = 1;
    this.retryIntervalId = setInterval(() => {
      if (count > this.maxRetries) {
        ElMessage.error({ plain: true, message: '网络连接超时，请检查网络！' });
        console.log(`重试超过 ${this.maxRetries} 次，终止重试`);
        clearInterval(this.retryIntervalId);
        this.retryIntervalId = null;
        return;
      }
      console.log(`进行第 ${count++} 次重试`);
      this.initWebSocket();
    }, 5000);
  }

  /**
   * 心跳机制
   */
  heartbeat() {
    if (this.heartbeatId) {
      clearInterval(this.heartbeatId);
    }
    this.heartbeatId = setInterval(() => {
      if (this.wsClient && this.wsClient.readyState === WebSocket.OPEN) {
        this.sendNotice({ type: 'heartbeat', message: 'heartbeat' });
      } else {
        console.warn('心跳失败，WebSocket 未连接');
      }
    }, 5000);
  }

  /**
   * 发送通知消息
   * @param {Object} obj - 通知消息对象
   */
  sendNotice(obj) {
    if (!this.wsClient || this.wsClient.readyState !== WebSocket.OPEN) {
      ElMessage({ type: 'error', message: '网络连接超时，请稍后再试！', plain: true });
      return;
    }
    this.wsClient.send(JSON.stringify(obj));
  }

  /**
   * 发送聊天消息
   * @param {Object} messageEntity - 消息实体
   */
  async sendMessage(messageEntity) {
    if (!this.wsClient || this.wsClient.readyState !== WebSocket.OPEN) {
      ElMessage({ type: 'error', message: '网络连接超时，请稍后再试！', plain: true });
      return;
    }

    const chatStore = useChatStore();
    const { type, status, isRead, content, sessionId, createUser, createTime } = messageEntity;

    try {
      const res = await window.ipcRenderer.invoke('save-message', messageEntity);
      if (res) {
        console.log('消息保存至本地 store');
        messageEntity.messageId = res;
        this.wsClient.send(JSON.stringify(messageEntityBuilder.sendMessageEntity(messageEntity)));
        if (chatStore.currentChat &&sessionId === chatStore.currentChat.sessionId) {
          chatStore.messageList.unshift({
            messageId: res,
            type: 1,
            content: content,
            createTime: messageEntity.createTime
          });
        }
        await chatStore.getSessionList();
      }
    } catch (error) {
      console.error('保存消息失败:', error);
      ElMessage({ type: 'error', message: '消息保存失败，请重试！', plain: true });
    }
  }
}

export default new WsUtil();
